/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.alien.admin.modules.deploy.service.impl;


import com.alien.admin.modules.deploy.domain.*;
import com.alien.admin.modules.deploy.repository.*;
import com.alien.admin.modules.deploy.service.DeployRecService;

import com.alien.admin.modules.deploy.service.dto.DeployRecDto;
import com.alien.admin.modules.deploy.service.dto.DeployRecQueryCriteria;

import com.alien.admin.modules.deploy.service.mapstruct.DeployRecMapper;

import com.alien.admin.modules.system.service.UserService;
import com.alien.admin.modules.system.service.dto.UserDto;
import com.alien.admin.utils.*;

import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.hibernate.query.criteria.internal.OrderImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.connection.SortParameters;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * @author zhouseyi
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-09-22
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class DeployRecServiceImpl implements DeployRecService {

    private final DeployRecRepository deployRecRepository;
    private final DeployRecMapper deployRecMapper;
    private final UserService userService;
    private final EntityManager entityManager;

    @Override
    public Map<String, Object> queryAll(DeployRecQueryCriteria criteria, Pageable pageable) {
        StopWatch stopWatch = StopWatch.createStarted();
        Page<DeployRec> page = deployRecRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        List<DeployRec> deployRecList = page.getContent();
        log.info("get page costTime:{}", stopWatch.getTime());
        for (DeployRec deployRec : deployRecList) {
            UserDto userDto = userService.findById(deployRec.getOperatorId());
            if (userDto == null) {
                continue;
            }
            deployRec.setOperatorName(userDto.getNickName());
        }
        stopWatch.stop();
        log.info("get operatorName costTime:{}", stopWatch.getTime());
        return PageUtil.toPage(page.map(deployRecMapper::toDto));
    }

    @Override
    public void deleteByEnvAndDeployTime(String env, Timestamp deployTime){
        deployRecRepository.deleteByEnvAndDeployTime(env, deployTime);
    }


    @Override
    public Map<String, Object> queryAll2(DeployRecQueryCriteria criteria, Pageable pageable) {

        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<DeployRec> query = cb.createQuery(DeployRec.class);
        Root<DeployRec> myRoot = query.from(DeployRec.class);
        // 确定要返回的字段
        query.multiselect(
                myRoot.get("id")
                , myRoot.get("env")
                , myRoot.get("projectId")
                , myRoot.get("projectName")
                , myRoot.get("stage")
                , myRoot.get("sourceBranch")
                , myRoot.get("operatorId")
                , myRoot.get("targetBranch")
                , myRoot.get("deployTime")
                , myRoot.get("deployStatus")

        ).where(QueryHelp.getPredicate(myRoot, criteria, cb))
                .orderBy(cb.desc(myRoot.get("id")));

        List<DeployRec> deployRecs = entityManager.createQuery(query)
                .setFirstResult((int) pageable.getOffset())
                .setMaxResults(pageable.getPageSize())
                .getResultList();

        for (DeployRec deployRec : deployRecs) {
            UserDto userDto = userService.findById(deployRec.getOperatorId());
            if (userDto == null) {
                continue;
            }
            deployRec.setOperatorName(userDto.getNickName());
        }

        Page<DeployRec> myPage = PageableExecutionUtils.getPage(deployRecs, pageable,
                () -> deployRecRepository.count((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));

        return PageUtil.toPage(myPage.map(deployRecMapper::toDto));
    }

    /**
     * 获取某个环境某个时间段内的部署记录数
     *
     * @param criteria
     * @return
     */
    @Override
    public int getDeployCount(DeployRecQueryCriteria criteria) {
        Long count = deployRecRepository.count((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        return count.intValue();
    }

    @Override
    public List<DeployRecDto> queryAll(DeployRecQueryCriteria criteria) {
        // 本身已经是按id递增，不需要按时间再排序
        return deployRecMapper.toDto(deployRecRepository.findAll((root, criteriaQuery, criteriaBuilder)
                -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public DeployRecDto findById(Long id) {
        DeployRec deployRec = deployRecRepository.findById(id).orElseGet(DeployRec::new);
        ValidationUtil.isNull(deployRec.getId(), "DeployRec", "id", id);
        return deployRecMapper.toDto(deployRec);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeployRecDto create(DeployRec resources) {
        return deployRecMapper.toDto(deployRecRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DeployRec resources) {
        DeployRec deployRec = deployRecRepository.findById(resources.getId()).orElseGet(DeployRec::new);
        ValidationUtil.isNull(deployRec.getId(), "DeployRec", "id", resources.getId());
        deployRec.copy(resources);
        deployRecRepository.save(deployRec);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            deployRecRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<DeployRecDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DeployRecDto deployRec : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("环境", deployRec.getEnv());
            map.put("项目id", deployRec.getProjectId());
            map.put("项目名称", deployRec.getProjectName());
            map.put("部署阶段", deployRec.getStage());
            map.put("源代码分支", deployRec.getSourceBranch());
            map.put(" targetBranch", deployRec.getTargetBranch());
            map.put("构建模板id", deployRec.getBuildTplId());
            map.put("构建id", deployRec.getBuildQueueId());
            map.put(" buildParam", deployRec.getBuildParam());
            map.put("构建日志", deployRec.getBuildLog());
            map.put("部署参数", deployRec.getDeployParam());
            map.put("部署模板id", deployRec.getDeployTplId());
            map.put(" operatorId", deployRec.getOperatorId());
            map.put(" deployTime", deployRec.getDeployTime());
            map.put("部署状态", deployRec.getDeployStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
